package books4africa

import grails.converters.XML

class UserController {
	
	def userService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }
	
	def info () {}

	
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def create() {
        [userInstance: new User(params)]
    }

    def save() {
		def user
       try {
		   user = userService.userSave(params)
       } catch (UserException ue){
	   	flash.message = ue.message
       }

		flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: user.id)
    }

    def show() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def edit() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def update() {
        def userInstance
		
		try{
			userInstance= userService.userUpdate(params)
			flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
		} catch (UserException ue){
			flash.message = ue.message
			redirect(action:"list")
		} catch (UpdateException ue){
			flash.message = ue.message
			redirect(action:'edit')
		}
		
    }

    def delete() {
		def userInstance
		
		try{
			userInstance = userService.deleteUser(params)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "list")
			
		} catch (UserException ue){
			flash.message = ue.message
			redirect(action:'list')
        }
    }
}
